<template>
  <div class="task-list-container">
    <!-- 分类标签栏 -->
    <div class="status-tabs">
      <div class="tabs-left">
        <el-tabs v-model="activeStatus" @tab-change="handleStatusChange">
          <el-tab-pane :label="$t('assets.taskList.all')" name="all" />
          <el-tab-pane :label="$t('assets.taskList.pending')" name="pending" />
          <el-tab-pane :label="$t('assets.taskList.grading')" name="grading" />
          <el-tab-pane :label="$t('assets.taskList.correction')" name="correction" />
          <el-tab-pane :label="$t('assets.taskList.correcting')" name="correcting" />
          <el-tab-pane :label="$t('assets.taskList.completed')" name="completed" />
        </el-tabs>
      </div>
      <div class="tabs-right">
        <el-button type="primary" @click="createTask">
          {{ $t('assets.dashboard.createTask') }}
        </el-button>
      </div>
    </div>

    <!-- 筛选功能栏 -->
    <div class="filter-section">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item :label="$t('assets.taskList.taskName') + ':'">
          <el-input v-model="searchForm.taskName" :placeholder="$t('assets.taskList.pleaseEnterTaskName')" clearable @input="handleSearch"
            style="width: 200px;" />
        </el-form-item>
        <el-form-item :label="$t('assets.taskList.subjectType') + ':'">
          <el-select v-model="searchForm.subjects" :placeholder="$t('assets.taskList.pleaseSelectSubject')" multiple clearable @change="handleSearch"
            style="width: 200px;">
            <el-option :label="$t('assets.subjects.math')" value="math" />
            <el-option :label="$t('assets.subjects.chinese')" value="chinese" />
            <el-option :label="$t('assets.subjects.english')" value="english" />
            <el-option :label="$t('assets.subjects.other')" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('assets.taskList.taskTime') + ':'">
          <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至" :start-placeholder="$t('assets.taskList.startDate')"
            :end-placeholder="$t('assets.taskList.endDate')" format="YYYY-MM-DD" value-format="YYYY-MM-DD" @change="handleSearch"
            style="width: 240px;" />
        </el-form-item>
        <el-form-item>
          <el-button @click="resetSearch">{{ $t('assets.taskList.reset') }}</el-button>
          <el-button type="primary" @click="handleSearch">{{ $t('assets.taskList.query') }}</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 任务列表表格 -->
    <div class="task-table" v-if="filteredTaskList.length > 0">
      <el-table :data="paginatedTaskList" :loading="loading" stripe border style="width: 100%" v-loading="loading">
        <el-table-column type="index" :label="$t('assets.taskList.serialNumber')" width="60" />
        <el-table-column prop="name" :label="$t('assets.taskList.taskName')" min-width="250">
          <template #default="{ row }">
            <div class="task-name-cell">
              <el-icon class="task-icon" :color="getSubjectColor(row.subject)">
                <Document />
              </el-icon>
              <div class="task-info">
                <div class="task-title clickable" @click="viewTaskDetail(row)">{{ row.title }}</div>
                <div class="task-subtitle">{{ row.description }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="studentCount" :label="$t('assets.taskList.relatedStudents')" width="120" align="center">
          <template #default="{ row }">
            <el-popover placement="top" :width="300" trigger="hover">
              <template #reference>
                <span class="student-count clickable" @click="showStudentDialog(row)">
                  {{ row.studentCount }}{{ $t('assets.taskList.people') }}
                </span>
              </template>
              <div class="student-tooltip-content">
                <div class="tooltip-title">{{ $t('assets.taskList.relatedStudents') }}</div>
                <div class="tooltip-students">
                  <div v-for="student in getTaskStudents(row)" :key="student.id" class="tooltip-student">
                    <span class="student-name">{{ student.name }}</span>
                    <span class="student-class">{{ student.classes.join('、') }}</span>
                  </div>
                </div>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column :label="$t('assets.taskList.taskTime')" width="180">
          <template #default="{ row }">
            <div class="task-time">
              <div>{{ formatDate(row.startTime) }}</div>
              <div>{{ formatDate(row.endTime) }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" :label="$t('assets.taskList.status')" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('assets.taskList.operation')" width="300" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button v-if="canShowAction(row.status, 'detail')" size="small" @click="viewTaskDetail(row)">
                {{ $t('assets.taskList.detail') }}
              </el-button>
              <el-button v-if="canShowAction(row.status, 'edit')" size="small" @click="editTask(row)">
                {{ $t('assets.taskList.edit') }}
              </el-button>
              <el-button v-if="canShowAction(row.status, 'grade')" size="small" type="primary" @click="gradeTask(row)">
                {{ $t('assets.taskList.goGrading') }}
              </el-button>
              <el-button v-if="canShowAction(row.status, 'correct')" size="small" type="warning"
                @click="correctTask(row)">
                {{ $t('assets.taskList.goCorrection') }}
              </el-button>
              <el-button v-if="canShowAction(row.status, 'copy')" size="small" @click="copyTask(row)">
                {{ $t('assets.taskList.copy') }}
              </el-button>
              <el-button v-if="canShowAction(row.status, 'delete')" size="small" type="danger" @click="deleteTask(row)">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-config-provider :locale="zhCn">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="filteredTaskList.length"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-config-provider>
      </div>
    </div>

    <!-- 空状态 -->
    <EmptyState
      v-else
      :text="$t('assets.dashboard.noTasksYet')"
      :button-text="$t('assets.dashboard.createTask')"
      @action="createTask"
    />

    <!-- 关联学生弹窗 -->
    <el-dialog v-model="studentDialogVisible" :title="$t('assets.taskList.relatedStudents')" width="500px">
      <div class="student-list">
        <div v-for="student in selectedTaskStudents" :key="student.id" class="student-item">
          <div class="student-name">{{ student.name }}</div>
          <div class="student-classes">{{ student.classes?.join('、') }}</div>
        </div>
      </div>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog v-model="deleteDialogVisible" :title="$t('assets.taskList.deleteConfirm')" width="400px">
      <p>{{ $t('assets.taskList.confirmDeleteTask') }}"{{ taskToDelete?.title }}"吗？</p>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">{{ $t('assets.cancel') }}</el-button>
        <el-button type="danger" @click="confirmDelete">{{ $t('assets.taskList.confirmDelete') }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document } from '@element-plus/icons-vue'
import { taskListStorage, type TaskListData } from '@/utils/taskListDB'
import { t as $t } from '@/plugins/i18nPlugin'
import { useStore } from '@/stores'
import EmptyState from '@/components/shared/Common/EmptyState.vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'

const router = useRouter()
const store = useStore()

// 响应式数据
const activeStatus = ref('all')
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(store.pageSize)

// 搜索表单
const searchForm = ref({
  taskName: '',
  subjects: [] as string[],
  dateRange: [] as string[]
})

// 教学任务数据
const taskList = ref<TaskListData[]>([])

// 弹窗相关
const studentDialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const selectedTaskStudents = ref<Array<{ id: string, name: string, classes: string[] }>>([])
const taskToDelete = ref<TaskListData | null>(null)

// 模拟学生数据
const mockStudents = [
  { id: '1', name: '张三河', classes: ['8年级冲刺班', '8年级冲刺班'] },
  { id: '2', name: '张二河', classes: ['8年级冲刺班'] },
  { id: '3', name: '张三河', classes: ['8年级冲刺班'] },
  { id: '4', name: '张三河', classes: ['8年级冲刺班', '8年级冲刺班'] },
  { id: '5', name: '张三河', classes: ['8年级冲刺班', '8年级冲刺班'] }
]

// 计算属性 - 筛选后的任务列表
const filteredTaskList = computed(() => {
  let filtered = [...taskList.value]

  // 按状态筛选
  if (activeStatus.value !== 'all') {
    filtered = filtered.filter(task => {
      switch (activeStatus.value) {
        case 'pending':
          return task.status === 'pending'
        case 'grading':
          return task.status === 'grading'
        case 'correction':
          return task.status === 'correction'
        case 'correcting':
          return task.status === 'correcting'
        case 'completed':
          return task.status === 'completed'
        default:
          return true
      }
    })
  }

  // 按任务名称筛选（模糊匹配）
  if (searchForm.value.taskName.trim()) {
    const keyword = searchForm.value.taskName.toLowerCase()
    filtered = filtered.filter(task =>
      task.title.toLowerCase().includes(keyword) ||
      task.description.toLowerCase().includes(keyword)
    )
  }

  // 按学科类型筛选（多选）
  if (searchForm.value.subjects.length > 0) {
    filtered = filtered.filter(task =>
      searchForm.value.subjects.includes(task.subject)
    )
  }

  // 按时间范围筛选
  if (searchForm.value.dateRange && searchForm.value.dateRange.length === 2) {
    const [startDate, endDate] = searchForm.value.dateRange
    filtered = filtered.filter(task => {
      const taskStartDate = task.startTime.split(' ')[0]
      const taskEndDate = task.endTime.split(' ')[0]
      return (taskStartDate >= startDate && taskStartDate <= endDate) ||
        (taskEndDate >= startDate && taskEndDate <= endDate) ||
        (taskStartDate <= startDate && taskEndDate >= endDate)
    })
  }

  return filtered
})

// 分页后的任务列表
const paginatedTaskList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredTaskList.value.slice(start, end)
})

// 加载任务列表
const loadTasks = async () => {
  loading.value = true
  try {
    await taskListStorage.init()
    const tasks = await taskListStorage.getTasks()
    // 按时间逆序排序（最新的在前面）
    taskList.value = tasks.sort((a, b) => {
      const timeA = new Date(a.createdAt || a.updatedAt).getTime()
      const timeB = new Date(b.createdAt || b.updatedAt).getTime()
      return timeB - timeA // 逆序排序，最新的在前面
    })
    console.log('任务列表加载成功:', taskList.value.length, '个任务')
  } catch (error) {
    console.error('加载任务列表失败:', error)
    ElMessage.error('加载任务列表失败')
    taskList.value = []
  } finally {
    loading.value = false
  }
}

// 状态变化处理
const handleStatusChange = (status: string) => {
  activeStatus.value = status
}

// 搜索处理
const handleSearch = () => {
  // 筛选逻辑在计算属性中处理，这里不需要额外操作
  console.log('执行搜索:', searchForm.value)
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    taskName: '',
    subjects: [],
    dateRange: []
  }
}

// 根据状态判断是否显示操作按钮
const canShowAction = (status: string, action: string): boolean => {
  const actionMap: Record<string, string[]> = {
    'pending': ['detail', 'edit', 'grade', 'copy', 'delete'],
    'grading': ['detail', 'grade', 'copy'],
    'correction': ['detail', 'correct', 'copy'],
    'correcting': ['detail', 'correct', 'copy'],
    'completed': ['detail', 'copy', 'delete']
  }

  return actionMap[status]?.includes(action) || false
}

// 查看任务详情
const viewTaskDetail = (task: TaskListData) => {
  console.log('查看任务详情，任务ID:', task.id)
  router.push({
    name: 'student-task-detail',
    params: {
      id: task.id
    }
  })
}

// 编辑任务
const editTask = (task: TaskListData) => {
  router.push({
    name: 'student-task-creation-wizard',
    query: {
      mode: 'edit',
      taskId: task.id
    }
  })
}

// 复制任务
const copyTask = (task: TaskListData) => {
  router.push({
    name: 'student-task-creation-wizard',
    query: {
      mode: 'copy',
      taskId: task.id
    }
  })
}

// 去批改
const gradeTask = (task: TaskListData) => {
  ElMessage.info('批改功能开发中...')
}

// 去订正
const correctTask = (task: TaskListData) => {
  ElMessage.info('订正功能开发中...')
}

// 删除任务
const deleteTask = (task: TaskListData) => {
  taskToDelete.value = task
  deleteDialogVisible.value = true
}

// 确认删除
const confirmDelete = async () => {
  if (!taskToDelete.value) return

  try {
    await taskListStorage.deleteTask(taskToDelete.value.id)
    ElMessage.success('学习任务删除成功')
    deleteDialogVisible.value = false
    taskToDelete.value = null
    await loadTasks() // 重新加载任务列表
  } catch (error) {
    console.error('删除任务失败:', error)
    ElMessage.error('删除任务失败，请重试')
  }
}

// 显示关联学生弹窗
const showStudentDialog = (task: TaskListData) => {
  selectedTaskStudents.value = mockStudents.slice(0, Math.min(task.studentCount, mockStudents.length))
  studentDialogVisible.value = true
}

// 获取任务关联学生（用于tooltip）
const getTaskStudents = (task: TaskListData) => {
  return mockStudents.slice(0, Math.min(3, task.studentCount))
}

// 获取学科颜色
const getSubjectColor = (subject: string): string => {
  const colorMap: Record<string, string> = {
    'math': '#2196f3',
    'chinese': '#9c27b0',
    'english': '#4caf50',
    'other': '#9e9e9e'
  }
  return colorMap[subject] || colorMap['other']
}

// 格式化日期
const formatDate = (dateStr: string): string => {
  if (!dateStr) return ''
  return dateStr.split(' ')[0] // 只显示日期部分
}

// 获取状态类型（用于el-tag）
const getStatusType = (status: string): string => {
  const typeMap: Record<string, string> = {
    'pending': 'warning',
    'grading': 'primary',
    'correction': 'info',
    'correcting': 'info',
    'completed': 'success'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string): string => {
  const textMap: Record<string, string> = {
    'pending': '待批改',
    'grading': '批改中',
    'correction': '待订正',
    'correcting': '订正中',
    'completed': '已完成'
  }
  return textMap[status] || status
}

// 创建学习任务
const createTask = () => {
  router.push('/student/learning-tasks/create')
}

// 分页处理函数
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
}

onMounted(async () => {
  console.log('学习任务列表页面加载完成')

  // 检查是否从任务创建页面跳转过来
  const route = useRoute()
  if (route.query.newTaskCreated === 'true' && route.query.taskName) {
    ElMessage.success(`学习任务 "${route.query.taskName}" 创建成功！`)
  }

  // 加载任务列表
  await loadTasks()

  // 如果有refresh参数，强制刷新列表
  if (route.query.refresh === 'true') {
    setTimeout(async () => {
      await loadTasks()
    }, 500) // 延迟500ms确保数据已保存
  }

  // 清理URL查询参数，防止页面刷新时重复显示消息
  if (Object.keys(route.query).length > 0) {
    router.replace({ path: route.path })
  }
})
</script>
<style
 scoped>
.task-list-container {
  padding: 24px;
  min-height: 100%;
  background: var(--content-bg-color);
  color: var(--text-color-primary);
  transition: background-color 0.3s ease, color 0.3s ease;
}

/* 分类标签栏 */
.status-tabs {
  margin-bottom: 24px;
  padding: 16px 24px;
  background: var(--card-bg-color);
  color: var(--text-color-primary);
  border-radius: 8px;
  box-shadow: var(--card-shadow);
  border: 1px solid var(--border-color-secondary);
  transition: background-color 0.3s ease, color 0.3s ease, border-color 0.3s ease;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tabs-left {
  flex: 1;
}

.tabs-right {
  flex-shrink: 0;
}

:deep(.el-tabs__header) {
  margin: 0;
}

:deep(.el-tabs__nav-wrap::after) {
  display: none;
}

:deep(.el-tabs__item) {
  font-size: 14px;
  color: #606266;
  padding: 0 20px;
  height: 40px;
  line-height: 40px;
}

:deep(.el-tabs__item.is-active) {
  color: #409EFF;
  font-weight: 600;
}

:deep(.el-tabs__active-bar) {
  background-color: #409EFF;
}

/* 筛选功能栏 */
.filter-section {
  margin-bottom: 24px;
  padding: 20px 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: end;
}

:deep(.el-form-item) {
  margin-bottom: 0;
}

:deep(.el-form-item__label) {
  font-size: 14px;
  color: #606266;
}

/* 任务列表表格 */
.task-table {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  min-height: auto;
}

/* 分页容器 */
.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px;
  border-top: 1px solid #f0f0f0;
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table__header) {
  background: #f8f9fa;
}

:deep(.el-table th) {
  background: #f8f9fa;
  color: #606266;
  font-weight: 600;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f0f0f0;
}

/* 任务名称单元格 */
.task-name-cell {
  display: flex;
  align-items: center;
  gap: 12px;
}

.task-icon {
  font-size: 20px;
}

.task-info {
  flex: 1;
}

.task-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
  cursor: pointer;
  transition: color 0.3s;
}

.task-title.clickable:hover {
  color: #409EFF;
}

.task-subtitle {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

/* 关联学生 */
.student-count {
  font-size: 16px;
  font-weight: 600;
  color: #409EFF;
  cursor: pointer;
  transition: all 0.3s;
}

.student-count.clickable:hover {
  color: #66b1ff;
  transform: scale(1.1);
}

/* 任务时间 */
.task-time {
  font-size: 14px;
  color: #606266;
  line-height: 1.4;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.action-buttons .el-button {
  margin: 0;
}

/* 关联学生弹窗样式 */
.student-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-height: 400px;
  overflow-y: auto;
}

.student-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.student-name {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.student-classes {
  font-size: 12px;
  color: #606266;
  background: #e3f2fd;
  padding: 4px 8px;
  border-radius: 12px;
}

/* 学生信息Tooltip样式 */
.student-tooltip-content {
  padding: 8px 0;
}

.tooltip-title {
  font-weight: 600;
  font-size: 13px;
  color: #303133;
  margin-bottom: 8px;
  padding-bottom: 4px;
  border-bottom: 1px solid #e4e7ed;
}

.tooltip-students {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.tooltip-student {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 0;
}

.tooltip-student .student-name {
  font-size: 12px;
  color: #303133;
  font-weight: 500;
}

.tooltip-student .student-class {
  font-size: 11px;
  color: #606266;
  background: #f0f2f5;
  padding: 2px 6px;
  border-radius: 8px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }

  :deep(.el-form-item) {
    margin-right: 0;
  }
}

@media (max-width: 768px) {
  .task-list-container {
    padding: 16px;
  }

  .action-buttons {
    flex-direction: column;
    align-items: flex-start;
  }

  :deep(.el-table .cell) {
    padding: 8px;
  }
}
</style>